package cmd

import (
	"os"
	"os/signal"
	"syscall"
	"ticket/config"
	"ticket/internal/auth"
	"ticket/internal/db"
	"ticket/internal/server"
	"ticket/pkg/logger"
	"ticket/pkg/path"

	"github.com/spf13/cobra"
	"github.com/spf13/viper"
	"go.uber.org/zap"
)

var rootCmd = &cobra.Command{
	Use:     "DevTicket",
	Version: "1.0.0",
	Short:   "A ticket system",
	Long:    `DevTicket is a simple ticket system. It allows you to manage tickets and projects.`,
	Run: func(cmd *cobra.Command, args []string) {
		configFile, _ := cmd.PersistentFlags().GetString("config")
		if !path.IsFile(configFile) {
			cmd.Help()
			return
		}
		config.LoadConfig(configFile)

		// 初始化日志
		logger.InitLogger()

		db.InitDB(viper.GetString("db.prefix"))

		if err := auth.NewAuthService(db.GormDB); err != nil {
			zap.S().Fatal("Failed to initialize auth service: ", err)
		}

		service := server.NewService()
		service.Start()

		quit := make(chan os.Signal, 1)
		signal.Notify(quit, syscall.SIGINT, syscall.SIGTERM)
		<-quit
		zap.S().Info("Shutting down server...")
		service.Stop()
	},
}

func init() {
	rootCmd.PersistentFlags().StringP("config", "c", "config/config.yaml", "config file path")
}

func Execute() {
	if err := rootCmd.Execute(); err != nil {
		panic(err)
	}
}
